import React, { Component } from 'react'

export default class Forms extends Component {
    constructor(props) {
        super(props)
        this.state = {
            inputValue: '',
            selectValue: 'coconut',
            isGoing: true,
            numberOfGuests: 2
        }
    }

    handleChange = (e) => {
        this.setState({
            inputValue: e.target.value
        })
    }

    handleSubmit = (e) => {
        alert('提交的名字：' + this.state.inputValue)
        e.preventDefault()
    }

    selectChange = (e) => {
        console.log("选择： ", e.target.value)
        this.setState({
            selectValue: e.target.value
        })
    }

    handleInputChange = (event) => {
        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name;

        this.setState({
            [name]: value
        });
    }

    render() {
        const { inputValue, selectValue, isGoing, numberOfGuests } = this.state

        return (
            <div>
                表单
                <hr />
                {inputValue}
                <form onSubmit={this.handleSubmit}>
                    <label>
                        名字：
                    <input type="text" value={inputValue} onChange={this.handleChange} />
                    </label>
                    <input type="submit" value="提交" />
                </form>
                <hr />
                <select value={selectValue} onChange={this.selectChange}>
                    <option value="grapefruit">葡萄柚</option>
                    <option value="lime">酸橙</option>
                    <option value="coconut">椰子</option>
                    <option value="mango">芒果</option>
                </select>
                <hr />
                处理多个输入 <br/>
                { isGoing ? '选中' : '未选中' } - { numberOfGuests }
                <br/>
                <label>
                    参与:
                <input
                        name="isGoing"
                        type="checkbox"
                        checked={isGoing}
                        onChange={this.handleInputChange} />
                </label>
                <br />
                <label>
                    来宾人数:
                <input
                        name="numberOfGuests"
                        type="number"
                        value={numberOfGuests}
                        onChange={this.handleInputChange} />
                </label>
            </div>

        )
    }
}